﻿using System.Collections.Concurrent;
using System.Text.Json;
using System.Text;
using WebApplication1.Tools;
using WebApplication1.Model;
using WebApplication1.Cmds.Provider;

namespace WebApplication1.Cmds.Imp
{
    public class HuaweiAuthClientProvider : IProvider<string>
    {

        protected bool CacheToken => true;

        public record HuaweiAuthRequestModel(string region, string apikey, string secret, string projectname);

        private static IDictionary<string, string> tokenCache = new ConcurrentDictionary<string, string>();

        public async Task<string> Execute(HttpCmdArgModel args)
        {
            var model = JsonSerializer.Deserialize<HuaweiAuthRequestModel>(JsonSerializer.Serialize(args.GetContent()));
            var requestData = new
            {
                auth = new
                {
                    identity = new
                    {
                        methods = new string[] { "hw_ak_sk" },
                        hw_ak_sk = new
                        {
                            access = new
                            {
                                key = model.apikey
                            },
                            secret = new
                            {
                                key = model.secret
                            }
                        }
                    },
                    scope = new
                    {
                        project = new
                        {
                            name = model.projectname
                        }
                    }
                }
            };
            var hashKey = BitConverter.ToString(
System.Security.Cryptography.MD5.HashData(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(requestData), 4, 8)))
                .Replace("-", "");
            if (CacheToken)
            {
                if (tokenCache.TryGetValue(hashKey, out var token))
                {
                    return token;
                }
            }
            var res = await new HttpClient().Request(args.GetRquestUrl(), args.method, requestData);
            if (res.HttpResponseMsg.IsSuccessStatusCode)
            {
                var obj = res.HttpResponseMsg.Headers.GetValues("X-Subject-Token").FirstOrDefault();
                if (CacheToken)
                {
                    tokenCache[hashKey] = obj;
                }
                return obj!;
            }
            else
            {
                return await res.HttpResponseMsg.Content.ReadAsStringAsync();
            }
        }
    }
}
